var hotkeyCode = localStorage["hotkey_value"]
var hotkeyShift = (localStorage["hotkey_shift"] === "true")
var hotkeyCtrl = (localStorage["hotkey_ctrl"] === "true")
var hotkeyAlt = (localStorage["hotkey_alt"] === "true")
var output = localStorage["output"]
var useCtrl = (localStorage["use_ctrl"] === "true")

$(document).ready(function() {
    var hotkeyText = ""
    if (hotkeyShift) hotkeyText += "SHIFT + "
    if (hotkeyCtrl) hotkeyText += "CTRL + "
    if (hotkeyAlt) hotkeyText += "ALT + "
    hotkeyText += String.fromCharCode(localStorage["hotkey_value"])
    $("#hotkey").val(hotkeyText)
    $("#sample_parameter").val(localStorage["sample_parameter"])
    $("#save_button").click(save)
    $("#hotkey").keydown(function(event) {
        if (event.which < 48 || event.which > 90) return
        hotkeyCode = event.which
        hotkeyShift = event.shiftKey
        hotkeyCtrl = event.ctrlKey
        hotkeyAlt = event.altKey
//        localStorage["hotkey_value"] = event.which
//        localStorage["hotkey_shift"] = event.shiftKey
//        localStorage["hotkey_ctrl"] = event.ctrlKey
//        localStorage["hotkey_alt"] = event.altKey
        var displayedText = ""
        if (event.shiftKey) displayedText += "SHIFT + "
        if (event.ctrlKey) displayedText += "CTRL + "
        if (event.altKey) displayedText += "ALT + "
        displayedText += String.fromCharCode(event.which)
        $("#hotkey").val(displayedText)
        event.preventDefault()
    })
    $("input[value=" + output + "]")[0].checked = true
    if (useCtrl) {
        $("#use_ctrl").attr("checked", "checked")
    }
})

function save() {
    localStorage["sample_parameter"] = $("#sample_parameter").val()
//    alert(hotkeyShift + " " + hotkeyCtrl)
    localStorage["hotkey_value"] = hotkeyCode
    localStorage["hotkey_shift"] = hotkeyShift
    localStorage["hotkey_ctrl"] = hotkeyCtrl
    localStorage["hotkey_alt"] = hotkeyAlt
    localStorage["output"] = $("input[name=output]:checked").val()
    if ($("#use_ctrl:checked").val() !== undefined) {
        localStorage["use_ctrl"] = true
        useCtrl = true
    } else {
        localStorage["use_ctrl"] = false
        useCtrl = false
    }
    chrome.windows.getAll({populate: true}, function(windows) {
        windows.forEach(function(window) {
            window.tabs.forEach(function(tab) {
                chrome.tabs.sendRequest(tab.id, {
                    type: "sethotkey",
                    value: hotkeyCode.toString(),
                    shift: hotkeyShift.toString(),
                    ctrl: hotkeyCtrl.toString(),
                    alt: hotkeyAlt.toString(),
                    useCtrl: useCtrl.toString()
                })
            })
        })
    })
}